package com.mysoft.gfyx.clue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.user.User;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.context.info.ContextInfo;
import com.mysoft.framework.core.function.authorization.AuthenticationUser;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.clue.controller.dto.PubAddCustomersRequestDto;
import com.mysoft.gfyx.clue.dao.CustomerDao;
import com.mysoft.gfyx.clue.dao.CustomerHistoryDao;
import com.mysoft.gfyx.clue.dao.entity.Customer;
import com.mysoft.gfyx.clue.dao.entity.CustomerHistory;
import com.mysoft.gfyx.clue.remoteservice.RemoteDeveloperService;
import com.mysoft.gfyx.clue.remoteservice.dto.CreditCodeBaseRequestDto;
import com.mysoft.gfyx.clue.service.CustomerHistoryService;
import com.mysoft.gfyx.clue.service.CustomerService;
import com.mysoft.gfyx.clue.service.dto.CustomerContactDto;
import com.mysoft.gfyx.clue.service.dto.CustomerDto;
import com.mysoft.gfyx.clue.service.dto.CustomerHistoryDto;
import com.mysoft.sdk.context.core.ThreadContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 描述：CustomerHistory客户历史记录 业务代码
 *
 * @author JavaSdk generator
 * @date 2022-11-15
 */
@Service
public class CustomerHistoryServiceImp extends AppService implements CustomerHistoryService {

    @Autowired
    private CustomerHistoryDao customerHistoryDao;

    @Autowired
    private RemoteDeveloperService remoteDeveloperService;

    @Autowired
    private ContextManager contextManager;

    @Override
    public CustomerHistoryDto selectById(String id) {
        CustomerHistory c = customerHistoryDao.selectById(id);
        return MappingUtil.getSimpleMapperFacade().map(c, CustomerHistoryDto.class);
    }

    @Override
    public CustomerHistoryDto getCustomerHistory(Map<String, Object> conditions) {

        QueryWrapper queryWrapper = new QueryWrapper();
        conditions.forEach((key, value) -> {
            queryWrapper.eq(key, value);
        });

        queryWrapper.last("limit 1");
        CustomerHistory c = customerHistoryDao.selectOne(queryWrapper);

        return MappingUtil.getSimpleMapperFacade().map(c, CustomerHistoryDto.class);
    }

    @Override
    public boolean addCustomerHistory(CustomerHistoryDto customerHistoryDto) {
        CustomerHistory cEntity = MappingUtil.getSimpleMapperFacade().map(customerHistoryDto, CustomerHistory.class);
        customerHistoryDao.insert(cEntity);
        return true;
    }

    @Override
    public CustomerHistoryDto getCustomerHistoryWithUnique(UUID CustomerResponsiblePersonGUID, String CreditCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("CustomerResponsiblePersonGUID", CustomerResponsiblePersonGUID);
        queryWrapper.eq("CreditCode", CreditCode);
        queryWrapper.last("limit 1");
        CustomerHistory c = customerHistoryDao.selectOne(queryWrapper);
        return MappingUtil.getSimpleMapperFacade().map(c, CustomerHistoryDto.class);
    }

    @Override
    public boolean addCustomerHistorys(Collection<CustomerHistoryDto> customerHistorysDto) {
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        Collection<String> creditCodes = new ArrayList<>();
        customerHistorysDto.forEach(c -> {
            c.setCustomerResponsiblePersonGUID(authenticationUser.getUserId());
            c.setCustomerResponsiblePersonName(authenticationUser.getUserName());
            creditCodes.add(c.getCreditCode());
        });

        if (creditCodes.size() == 0) {
            throw new BusinessLogicException("您尚未选择客户");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("CustomerResponsiblePersonGUID", authenticationUser.getUserId());
        queryWrapper.in("CreditCode", creditCodes);
        List<CustomerHistory> exits = customerHistoryDao.selectList(queryWrapper);
        Set<String> exitsCreditCode = new HashSet<>();
        exits.forEach(e -> {
            exitsCreditCode.add(e.getCreditCode());
        });

        Collection<CustomerHistory> customerHistorys = new ArrayList<>();
        customerHistorysDto.forEach(c -> {
            if (!exitsCreditCode.contains(c.getCreditCode())) {
                customerHistorys.add(MappingUtil.getSimpleMapperFacade().map(c, CustomerHistory.class));
            }

        });
        if (customerHistorys.size() > 0) {
            customerHistoryDao.insertBatchWithDynamicExt(customerHistorys);
        }

        return true;
    }

    @Override
    public boolean addCustomersAndContacts(PubAddCustomersRequestDto pubAddCustomersDto) {
        List<CustomerContactDto> contacts = pubAddCustomersDto.getContact();
        contacts.forEach(contactRow -> {//循环负责人
            List<CustomerDto> customersDto = pubAddCustomersDto.getCustomers(); //客户列表
            List<CustomerHistoryDto> customerHistorysDto = new ArrayList<>(); //客户历史
            Collection<String> creditCodes = new ArrayList<>();
            customersDto.forEach(c -> {
                c.setCustomerResponsiblePersonGUID(contactRow.getCustomerResponsiblePersonGUID());
                c.setCustomerResponsiblePersonName(contactRow.getCustomerResponsiblePersonName());
                creditCodes.add(c.getCreditCode());

                CustomerHistoryDto customerHistoryDto = MappingUtil.getSimpleMapperFacade().map(c, CustomerHistoryDto.class);//客户转为客户历史
                customerHistorysDto.add(customerHistoryDto);
            });


            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("CustomerResponsiblePersonGUID", contactRow.getCustomerResponsiblePersonGUID());
            queryWrapper.in("CreditCode", creditCodes);
            List<CustomerHistory> exits = customerHistoryDao.selectList(queryWrapper);
            Set<String> exitsCreditCode = new HashSet<>();
            exits.forEach(e -> {
                exitsCreditCode.add(e.getCreditCode());
            });

            Collection<CustomerHistory> customerHistorys = new ArrayList<>();
            customerHistorysDto.forEach(c -> {
                if (!exitsCreditCode.contains(c.getCreditCode())) {
                    customerHistorys.add(MappingUtil.getSimpleMapperFacade().map(c, CustomerHistory.class));
                }

            });
            if (customerHistorys.size() > 0) {
                customerHistoryDao.insertBatchWithDynamicExt(customerHistorys);
            }
        });

        return true;
    }
}